package com.longrise.co.ui.mine.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.appeaser.sublimepickerlibrary.datepicker.SelectedDate;
import com.appeaser.sublimepickerlibrary.recurrencepicker.SublimeRecurrencePicker;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.co.R;
import com.longrise.co.api.CommonPara;
import com.longrise.co.ui.carfiles.model.UploadBean;
import com.longrise.co.ui.carfiles.widget.AddPhotoDialog;
import com.longrise.co.ui.mine.contract.MineContract;
import com.longrise.co.ui.mine.model.MineModel;
import com.longrise.co.ui.mine.model.VerifiedCarBean;
import com.longrise.co.ui.mine.presenter.MinePresenter;
import com.longrise.co.utils.Constants;
import com.longrise.co.utils.DatePickerDialogUtils;
import com.longrise.co.utils.StringUtils;
import com.longrise.co.utils.SublimePickerFragment;
import com.ly.common.base.BaseFragment;
import com.ly.common.commonutils.ImageLoaderUtils;
import com.ly.common.commonutils.TimeCountUtil;
import com.ly.common.commonutils.TimeUtil;
import com.ly.common.security.EnCryptDeCrypt2;

import java.io.File;
import java.util.Date;

import butterknife.Bind;
import butterknife.OnClick;

import static com.longrise.co.R.id.register_date_et;

/**
 * Created by luoyang on 2017-7-20.
 */

public class CertifiedVehicleFragment extends BaseFragment<MinePresenter, MineModel> implements MineContract.AuthCarView<VerifiedCarBean>,TakePhoto.TakeResultListener,InvokeListener, AddPhotoDialog.OnSelectPhotoListener {

    @Bind(R.id.head_title)
    TextView headTitle;
    @Bind(R.id.driving_license)
    ImageView drivingLicense;
    @Bind(R.id.small_car_iv)
    ImageView smallCarIv;
    @Bind(R.id.middle_car_iv)
    ImageView middleCarIv;
    @Bind(R.id.big_car_iv)
    ImageView bigCarIv;
    @Bind(R.id.other_car_iv)
    ImageView otherCarIv;
    @Bind(R.id.car_no_et)
    EditText carNoEt;
    @Bind(R.id.frame_number_et)
    EditText frameNumberEt;
    @Bind(R.id.register_date_et)
    TextView registerDateEt;
    @Bind(R.id.mobile_et)
    EditText mobileEt;
    @Bind(R.id.input_ver_code_et)
    EditText inputVerCodeEt;
    @Bind(R.id.get_code_tv)
    TextView getCodeTv;
    @Bind(R.id.car_photo_iv)
    ImageView carPhotoIv;
    @Bind(R.id.engine_number_et)
    EditText engineNumberEt;

    private int mCurrentCarType = 1;

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private Uri imageUri;
    private TImage mCurrentImage;
    private TimeCountUtil mTimeCount;

    private UploadBean mUploadBean;

    private boolean isSuccess = false;

    private String imageInfo;

    private AddPhotoDialog mAddPhotoDialog;

    @Override
    protected int getLayoutResource() {
        return R.layout.fg_auth_car;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this , mModel);
    }



    @Override
    protected void initView() {
        setText(headTitle, "认证车辆");
        initPhotoSelect();
    }

    private void initPhotoSelect() {
        File file=new File(Environment.getExternalStorageDirectory(), "/temp/"+System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists())file.getParentFile().mkdirs();
        imageUri = Uri.fromFile(file);
        configTakePhotoOption();
    }

    private void configTakePhotoOption(){
        TakePhotoOptions.Builder builder=new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(false);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    private void initAddPhotoDialog() {
        mAddPhotoDialog = new AddPhotoDialog(getContext(), R.style.dialog_style);
        mAddPhotoDialog.setCanceledOnTouchOutside(true);
        mAddPhotoDialog.setOnSelectPhotoListener(this);
//        mAddPhotoDialog.create();

    }

    @OnClick({R.id.head_back, R.id.driving_license, R.id.small_car_ll, R.id.middle_car_ll, R.id.big_car_ll, R.id.other_car_ll, R.id.get_code_tv, R.id.car_photo_iv, R.id.confirm, register_date_et})
    public void onViewClicked(View view) {
        if(checkDoubleClick()) {
            switch (view.getId()) {
                case R.id.head_back:
                    _mActivity.onBackPressed();
                    break;
                case R.id.driving_license:
                    if(mAddPhotoDialog == null) {
                        initAddPhotoDialog();
                    }
                    mAddPhotoDialog.show();
//                    takePhoto.onPickFromGallery();
                    break;
                case R.id.small_car_ll:
                    setCarType(1);
                    break;
                case R.id.middle_car_ll:
                    setCarType(2);
                    break;
                case R.id.big_car_ll:
                    setCarType(3);
                    break;
                case R.id.other_car_ll:
                    setCarType(9);
                    break;
                case R.id.get_code_tv:
                    mPresenter.sendSmsRequest(mobileEt.getText().toString(), "4");
                    break;
                case R.id.confirm:
                    try {
                        if (checkAuthCarPara()) {
                            EntityBean bean = new EntityBean();

                            String enCarNo = EnCryptDeCrypt2.getInstance().EnCrypt(carNoEt.getText().toString());
                            bean.set("userflag", CommonPara.getInstance().getUserFlag());
                            bean.set("carno", carNoEt.getText().toString());
                            bean.set("vin", frameNumberEt.getText().toString());
                            bean.set("cartype", String.valueOf(mCurrentCarType));
                            bean.set("mobile", mobileEt.getText().toString());
                            bean.set("smscode", inputVerCodeEt.getText().toString());
                            bean.set("carimg", imageInfo);
                            bean.set("registerdate", registerDateEt.getText().toString());
                            bean.set("user", CommonPara.getInstance().getUser());
                            bean.set("enginenumber",engineNumberEt.getText().toString());
                            bean.set("sign", enCarNo);
                            mPresenter.verifiedCar(bean);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                case R.id.register_date_et:
                    DatePickerDialogUtils.showDialog(mFragmentCallback, this.getChildFragmentManager());
                    break;

            }
        }

    }

    private boolean checkAuthCarPara() {
        if(imageInfo == null) {
            showErrorTip("请上传行驶证信息");
            return false;
        }
        if(carNoEt == null || com.ly.common.commonutils.StringUtils.isEmpty(carNoEt.getText().toString())) {
            showErrorTip("请输入车牌号");
            return false;
        }
        if(!com.ly.common.commonutils.StringUtils.isCar(carNoEt.getText().toString().toUpperCase())) {
            showErrorTip("请输入正确的车牌号");
            carNoEt.setText(carNoEt.getText().toString().toUpperCase());
            return false;
        }
        carNoEt.setText(carNoEt.getText().toString().toUpperCase());

        if(frameNumberEt == null || com.ly.common.commonutils.StringUtils.isEmpty(frameNumberEt.getText().toString())) {
            showErrorTip("请输入车架号");
            return false;
        }
        frameNumberEt.setText(frameNumberEt.getText().toString().toUpperCase());

        if(engineNumberEt == null || com.ly.common.commonutils.StringUtils.isEmpty(engineNumberEt.getText().toString())) {
            showErrorTip("请输入发动机号");
            return false;
        }
        engineNumberEt.setText(engineNumberEt.getText().toString().toUpperCase());

        if(registerDateEt == null || com.ly.common.commonutils.StringUtils.isEmpty(registerDateEt.getText().toString()) || "请选择日期".equals(registerDateEt.getText().toString())) {
            showErrorTip("请选择注册日期");
            return false;
        }
        if(mobileEt == null || com.ly.common.commonutils.StringUtils.isEmpty(mobileEt.getText().toString())) {
            showErrorTip("请输入手机号");
            return false;
        }
        if(!com.ly.common.commonutils.StringUtils.isChinaPhoneLegal(mobileEt.getText().toString())) {
            showErrorTip("请输入正确的手机号");
            return false;
        }

        if(inputVerCodeEt == null || com.ly.common.commonutils.StringUtils.isEmpty(inputVerCodeEt.getText().toString())) {
            showErrorTip("请输入手机号验证码");
            return false;
        }


        return true;
    }

    private void setCarType(int carType) {
        this.mCurrentCarType = carType;
        smallCarIv.setBackgroundResource(R.drawable.radio_unselect);
        middleCarIv.setBackgroundResource(R.drawable.radio_unselect);
        bigCarIv.setBackgroundResource(R.drawable.radio_unselect);
        otherCarIv.setBackgroundResource(R.drawable.radio_unselect);

        switch (mCurrentCarType) {
            case 1 :
                smallCarIv.setBackgroundResource(R.drawable.radio_select);
                break;
            case 2 :
                middleCarIv.setBackgroundResource(R.drawable.radio_select);
                break;
            case 3 :
                bigCarIv.setBackgroundResource(R.drawable.radio_select);
                break;
            case 9 :
                otherCarIv.setBackgroundResource(R.drawable.radio_select);
                break;
        }
    }

    @Override
    public void requestSuccess(VerifiedCarBean carCertifiedBean) {
        showLongToast("恭喜您，认证成功！");
        mRxManager.post(Constants.RX_EVENT_AUTH_CAR, "3");
        mRxManager.post(Constants.RX_EVENT_REFRESH_MINE, "");
        mRxManager.post(Constants.RX_EVENT_REFRESH_CAR_FILE, "");
        mRxManager.post(Constants.RX_EVENT_REFRESH_HOME, "");
        isSuccess = true;
    }

    @Override
    public void onRequestComplete() {
        if(isSuccess) {
            _mActivity.onBackPressed();
        }
    }

    public static CertifiedVehicleFragment newInstance() {
        return new CertifiedVehicleFragment();
    }



    SublimePickerFragment.Callback mFragmentCallback = new SublimePickerFragment.Callback() {
        @Override
        public void onCancelled() {

        }

        @Override
        public void onDateTimeRecurrenceSet(SelectedDate selectedDate,
                                            int hourOfDay, int minute,
                                            SublimeRecurrencePicker.RecurrenceOption recurrenceOption,
                                            String recurrenceRule) {
            Date date = selectedDate.getFirstDate().getTime();
            String newDateStr = TimeUtil.formatData(TimeUtil.dateFormatYMD, date.getTime()/1000);
            registerDateEt.setText(newDateStr);
        }
    };

    @Override
    public void takeSuccess(TResult result) {
        try {
            if(result != null && result.getImage() != null) {
                mCurrentImage = result.getImage();
                imageInfo = StringUtils.File2Base64(result.getImage().getOriginalPath());
                ImageLoaderUtils.display(getContext(), drivingLicense, mCurrentImage.getOriginalPath());
//                mPresenter.uploadPhoto(imageInfo, "5");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void takeFail(TResult result, String msg) {
        showErrorTip(msg);
    }

    @Override
    public void takeCancel() {

    }

    /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(getActivity(),type,invokeParam,this);
    }

    @Override
    public void sendMsgSuccess() {
        showLongToast("发送验证码成功");
        getCodeTv.setEnabled(false);
        if (mTimeCount == null) {
            mTimeCount = new TimeCountUtil(60 * 1000, 1000, getCodeTv);
        }
        mTimeCount.start();
    }

    @Override
    public void uploadSuccess(UploadBean bean) {
        showLongToast("上传图片成功!");
        mUploadBean =  bean;
        if(mCurrentImage != null && !com.ly.common.commonutils.StringUtils.isEmpty(mCurrentImage.getOriginalPath())) {
            ImageLoaderUtils.display(getContext(), drivingLicense, mCurrentImage.getOriginalPath());
        }

    }

    @Override
    public void onSelect(int type) {
        switch (type) {
            case AddPhotoDialog.SELECT_ALBUM :
                //选择相册
                takePhoto.onPickFromGallery();
//                        onPickMultiple(MAX_UPLOAD_IMAGE + 1 - mAdapter.getData().size());
                break;
            case AddPhotoDialog.SELECT_PHOTO :
                //拍照
                takePhoto.onPickFromCapture(imageUri);
                break;
            case AddPhotoDialog.SELECT_CANCEL :
                break;
        }
        mAddPhotoDialog.dismiss();
    }
}
